package com.tg.app.activity.device.settings;

import android.annotation.SuppressLint;
import android.content.Intent;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.view.Window;
import android.widget.ListView;

import androidx.annotation.NonNull;
import androidx.annotation.Nullable;

import com.appbase.custom.base.SettingData;
import com.appbase.custom.constant.DoubleLightModeConstants;
import com.bumptech.glide.request.RequestOptions;
import com.tange.module.camera.hub.CameraHub;
import com.tg.app.R;
import com.tg.app.TGDevice;
import com.tg.app.activity.base.DeviceSettingsBaseActivity;
import com.tg.app.activity.device.DeviceSettingsActivity;
import com.tg.app.adapter.SettingAdapter;
import com.tg.app.camera.AVIOCTRLDEFs;
import com.tg.app.camera.Camera;
import com.tg.appcommon.android.TGLog;
import com.tg.appcommon.android.TGToast;
import com.tg.appcommon.transform.GrayscaleTransformation;
import com.tg.data.bean.DeviceSettingsInfo;
import com.tg.data.media.OnICameraListener;

import java.util.ArrayList;

public class DoubleLightAutoActivity extends DeviceSettingsBaseActivity implements OnICameraListener {
    private final ArrayList<SettingData> datas = new ArrayList<>();
    private SettingAdapter adapter;
    Camera camera;
    DeviceSettingsInfo info;

    private int selectMode;
    private int oldMode;
    int clickPosition;
    private final static int EVENT_NIGHT = 0;
    private final static int EVENT_NIGHT_BODY = 1;
    private final static int EVENT_NIGHT_BODY_LIGHT = 2;
    private final static int EVENT_NIGHT_BODY_LIGHT_OFF = 3;
    private final Handler handler = new Handler() {
        @Override
        public void handleMessage(Message msg) {
            switch (msg.what) {
                case EVENT_NIGHT:
                    night();
                    break;
                case EVENT_NIGHT_BODY:
                    nightBody();
                    break;
                case EVENT_NIGHT_BODY_LIGHT:
                    handler.postDelayed(new Runnable() {
                        @Override
                        public void run() {
                            setDoubleModeView();
                        }
                    }, 2000);
                    break;
                case EVENT_NIGHT_BODY_LIGHT_OFF:
                    handler.postDelayed(new Runnable() {
                        @Override
                        public void run() {
                            setInfraredModeView();
                        }
                    }, 2000);

                    break;
            }
        }
    };

    public DoubleLightAutoActivity() {

    }

    @Override
    protected void onSetupFailed() {
        setPositionByMode(oldMode);
    }

    private void setPositionByMode(int oldMode) {
        clickPosition = oldMode;
        if (oldMode == DoubleLightModeConstants.DOUBLE_LIGHT_MODE_AUTO) {
            clickPosition = 0;
            setDoubleModeView();
        } else if (oldMode == DoubleLightModeConstants.DOUBLE_LIGHT_MODE_ON) {
            setFullColorModeView();
            clickPosition = 2;
        } else if (oldMode == DoubleLightModeConstants.DOUBLE_LIGHT_MODE_OFF) {
            setInfraredModeView();
            clickPosition = 1;
        }
        setFlag(clickPosition);
    }

    @Override
    protected void onCreate(@SuppressLint("UnknownNullness") @Nullable Bundle savedInstanceState) {
        requestWindowFeature(Window.FEATURE_NO_TITLE);//remove title bar  即隐藏标题栏
        hideActionBar();
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_double_light_auto);
        initView();

        Intent intent = getIntent();
        info = intent.getParcelableExtra(DeviceSettingsActivity.EXT_DEVICE_INFO);
        camera = info == null ? null : CameraHub.getInstance().getCamera(info.uuid);
        if (camera != null) {
            camera.registerICameraListenerAndConnect(this);
        }
        initData();
        backClickEvent();
    }

    @Override
    protected void initView() {
        modifyToolBar(R.string.settings_double_light);
        adapter = new SettingAdapter(datas, this);
        adapter.setFirstNormal(true);
        ListView listView = findViewById(R.id.double_light_list);
        listView.setAdapter(adapter);
        listView.setOnItemClickListener((parent, view, position, id) -> {
            if (!TGDevice.getInstance().isNetwork(camera)) {
                TGToast.showToast(R.string.txt_network_anomaly);
            } else {
                clickPosition = position;
                switch (position) {
                    case 0:
                        sendDoubleModeCMD();
                        setDoubleModeView();
                        break;
                    case 1:
                        sendInfraredModeCMD();
                        setInfraredModeView();
                        break;


                    case 2:
                        sendFullColorModeCMD();
                        setFullColorModeView();
                        break;
                }
                setFlag(clickPosition);
            }
        });

    }

    void sendDoubleModeCMD() {
        setDoubleLight(DoubleLightModeConstants.DOUBLE_LIGHT_MODE_AUTO);
    }

    void sendInfraredModeCMD() {
        setDoubleLight(DoubleLightModeConstants.DOUBLE_LIGHT_MODE_OFF);//红外 2
    }

    void sendFullColorModeCMD() {
        setDoubleLight(DoubleLightModeConstants.DOUBLE_LIGHT_MODE_ON);//开 全彩1
    }

    void setDoubleModeView() {
        handler.removeCallbacksAndMessages(null);
        handler.sendEmptyMessage(EVENT_NIGHT);
        handler.sendEmptyMessageDelayed(EVENT_NIGHT_BODY, 2000);
        handler.sendEmptyMessageDelayed(EVENT_NIGHT_BODY_LIGHT, 3000);
    }

    void setInfraredModeView() {

        handler.removeCallbacksAndMessages(null);
        handler.sendEmptyMessage(EVENT_NIGHT);
        handler.sendEmptyMessageDelayed(EVENT_NIGHT_BODY, 2000);
        handler.sendEmptyMessageDelayed(EVENT_NIGHT_BODY_LIGHT_OFF, 3000);
    }

    void setFullColorModeView() {
        handler.removeCallbacksAndMessages(null);
    }

    private void night() {
        setNightViewBg(R.mipmap.night_vision_night);
    }

    @SuppressLint("CheckResult")
    private void setNightViewBg(int resId) {
        if (isFinishing()) return;
        RequestOptions requestOptions = new RequestOptions().dontAnimate();
        GrayscaleTransformation transformation = new GrayscaleTransformation();
        RequestOptions other = RequestOptions.bitmapTransform(transformation);
        requestOptions.apply(other);

    }



    private void nightBody() {
        setNightViewBg(R.mipmap.night_vision_night_body);

    }


    private void initData() {
        int type = info != null ? info.doubleLight : -1;

        SettingData disable = new SettingData(getString(R.string.settings_double_light_infrared), 0);
        SettingData auto = new SettingData(getString(R.string.settings_double_light_double), 0);
        SettingData enable = new SettingData(getString(R.string.settings_double_light_full_color), 0);
        datas.add(auto);
        datas.add(disable);
        datas.add(enable);

        if (type == -1) {
            type = 0;
            sendDoubleModeCMD();
        }

        oldMode = type;
        selectMode = type;

        setPositionByMode(type);
    }

    private void setDoubleLight(int type) {
        if (camera != null) {
            oldMode = selectMode;
            selectMode = type;
            camera.sendIOCtrl(AVIOCTRLDEFs.IOTYPE_USEREX_IPCAM_SET_DOUBLELIGHT_REQ, AVIOCTRLDEFs.SMsgAVIoctrlSetDoubleLightReq.parseContent(type));
        }
    }

    private void setFlag(int position) {
        if (info != null) {
            info.doubleLight = position;
        }
        for (int i = 0; i < datas.size(); i++) {
            if (i == position) {
                datas.get(i).setFlag(1);
            } else {
                datas.get(i).setFlag(0);
            }
        }
        adapter.notifyDataSetChanged();

    }

    @Override
    protected void onPause() {
        super.onPause();
        if (camera != null) {
            camera.unregisterICameraListener(this);
        }
    }

    @Override
    protected void onStop() {
        super.onStop();
        handler.removeCallbacksAndMessages(null);
    }

    @Override
    public void receiveUpdateConnectStates(int state) {
        TGLog.d("state = " + state);
    }

    @Override
    public void receiveIOCtrlData(int type, @NonNull byte[] data) {
        if (type == AVIOCTRLDEFs.IOTYPE_USEREX_IPCAM_SET_DOUBLELIGHT_RESP) {
            runOnUiThread(() -> {
                completeSend();
                if (info != null) {
                    info.doubleLight = selectMode;
                }
                sendUpdateSettingBroadcast(info);
            });
        }
    }
}